﻿using System;
using System.Collections.Generic;
using System.Text;
using AgencyManagerSystem.Model;
using AgencyManagerSystem.DataUpdater;
using AgencyManagerSystem.Common;
using AgencyManagerSystem.DataFetcher;

namespace AgencyManagerSystem.Core
{
    public class DomainUpdaterCreator : BaseUpdaterCreator<DomainModel>
    {
        public DomainUpdater CreateDomainUpdaterInstance()
        {
            DomainUpdater domainUpdater = new DomainUpdater(new DomainFetcher());
            domainUpdater.DataUpdating += FlagAndApproveFlagValid;
            domainUpdater.DataUpdating += DataNotEmpty;
            domainUpdater.DataUpdating += CodeUnique;
            domainUpdater.DataDeleting += RightTableExists;
            return domainUpdater;
        }

        private void RightTableExists(BaseUpdater<DomainModel> sender, DataDeletingEventArgs<DomainModel> e)
        {
            if (e.Delete == null)
                return;
            RoleUserFetcher roleUserFetcher = new RoleUserFetcher();
            var roleUsrs = roleUserFetcher.ListByDomain(e.Delete.AutoId);
            if(roleUsrs.Count>0)
            {
                e.Cancel = true;
                e.Message = String.Format("代码[{0}]已经被使用不能删除", e.Delete.Code);
                return;
            }
        }

        private void CodeUnique(BaseUpdater<DomainModel> sender, DataUpdatingEventArgs<DomainModel> e)
        {
            if (e.Insert == null)
                return;
            DomainFetcher domainFetcher = new DomainFetcher();
            DomainModel domainModel = domainFetcher.GetByCode(e.Insert.Code);
            if(domainModel!=null&&domainModel.AutoId!=e.Insert.AutoId)
            {
                e.Cancel = true;
                e.Message = String.Format("代码[{0}]已经被占用", e.Insert.Code);
                return;
            }
        }

        private void DataNotEmpty(BaseUpdater<DomainModel> sender, DataUpdatingEventArgs<DomainModel> e)
        {
            if (e.Insert == null)
                return;
            if(String.IsNullOrWhiteSpace(e.Insert.Code)||String.IsNullOrWhiteSpace(e.Insert.Name))
            {
                e.Cancel = true;
                e.Message = "代码或名称不能为空";
                return;
            }
        }
    }
}
